/**
 * BaseTask.java
 * 
 * Create Version: 1.0
 * Author: 刘洪政
 * Create Date: 2012-4-23
 */
package ysyh55.android.base.task;

import java.io.IOException;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import ysyh55.android.base.exception.HttpAuthException;
import ysyh55.android.base.exception.HttpException;
import ysyh55.android.base.exception.HttpRefusedException;
import ysyh55.android.base.exception.HttpServerException;
import ysyh55.android.base.exception.TaskResultException;
import ysyh55.android.base.util.NullUtils;

/**
 * BaseTask 异步任务基类
 * 
 * @author 刘洪政
 */
public abstract class BaseTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {
	protected String message;
	protected Boolean error = false;
	protected Context context;
	protected ProgressDialog loadMask;
	protected Boolean hasLoadMask = false;

	public BaseTask(Context context) {
		this.context = context;
	}

	public BaseTask(Context context, String loadingMsg) {
		this.context = context;
		this.hasLoadMask = NullUtils.isNotEmpty(loadingMsg);
		this.message = loadingMsg;
	}

	@Override
	protected Result doInBackground(Params... params) {
		try {
			return doInBack(params);
		} catch (HttpAuthException e) {
			message = "你无权访问该页面。";
		} catch (HttpRefusedException e) {
			message = "服务器拒绝访问。";
		} catch (HttpServerException e) {
			message = "系统调用异常， 服务器返回代码：" + e.getStatusCode();
		} catch (IOException e) {
			message = "网络错误，请稍后再试。";
		} catch (Exception e) {
			Log.e("BaseTask", e.toString());
			message = e.getMessage();
			
			e.printStackTrace();
		}

		error = true;
		return null;
	}

	@Override
	protected void onPostExecute(Result result) {
		super.onPostExecute(result);

		if (this.hasLoadMask) {
			this.loadMask.dismiss();
		}

		if (error) {
			onError();
		} else {
			onSuccess(result);
		}
	};

	protected String getString(int resId) {
		return context.getString(resId);
	}

	protected void onError() {
		Toast.makeText(context, message, Toast.LENGTH_LONG).show();
	}

	protected void onPreExecute() {
		if (this.hasLoadMask) {
			if (NullUtils.isNull(this.loadMask)) {
				this.loadMask = ProgressDialog.show(this.context, null, this.message);
			} else {
				this.loadMask.setMessage(this.message);
				this.loadMask.show();
			}
		}
	}

	protected abstract void onSuccess(Result result);

	protected abstract Result doInBack(Params... params) throws HttpException, IOException, TaskResultException;
}
